package transforms;

import java.util.ListIterator;

import org.objectweb.asm.tree.FieldNode;

import com.rshacking.rhf.files.ClassContainer;
import com.rshacking.rhf.updater.Transform;
import com.rshacking.rhf.updater.hooks.ClassHook;
import com.rshacking.rhf.updater.hooks.HooksList;

public class ConnectionTransform extends Transform {

    @Override
    public boolean canActivate(final HooksList hooks, final ClassContainer cc) {
        return cc.containsFieldType("Ljava/net/Socket;")
                && cc.containsFieldType("Ljava/io/OutputStream;");
    }

    @Override
    public boolean execute(final HooksList hooks, final ClassContainer cc) {
        final ClassHook ch = hooks.add("Connection", cc.getName());
        final ListIterator<?> i = cc.getASM().fields.listIterator();
        while (i.hasNext()) {
            final FieldNode fn = (FieldNode) i.next();
            if (fn.desc.equals("Ljava/net/Socket;")) {
                ch.add("socket", fn);
            } else if (fn.desc.equals("Ljava/io/OutputStream;")) {
                ch.add("outputStream", fn);
            } else if (fn.desc.equals("Ljava/io/InputStream;")) {
                ch.add("inputStream", fn);
            }
        }
        return true;
    }

}
